package org.light4j.springboot.aop.aspect;

import java.lang.reflect.Method;
import java.util.Arrays;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.light4j.springboot.aop.annotation.Action;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
public class LogAspect {

	// pointCut
	@Pointcut("@annotation(org.light4j.springboot.aop.annotation.Action)")
	public void log() {

	}

	/**
	 * 前置通知
	 */
	@Before("log()")
	public void doBeforeController(JoinPoint joinPoint) {
		MethodSignature signature = (MethodSignature) joinPoint.getSignature();
		Method method = signature.getMethod();
		Action action = method.getAnnotation(Action.class);
		System.out.println("before action名称 " + action.value()); // ⑤
		// 接收到请求，记录请求内容
		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = attributes.getRequest();
		// 记录下请求内容
		System.out.println("URL : " + request.getRequestURL().toString());
		System.out.println("HTTP_METHOD : " + request.getMethod());
		System.out.println("IP : " + request.getRemoteAddr());
		System.out.println("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
		System.out.println("ARGS : " + Arrays.toString(joinPoint.getArgs()));
	}

	/**
	 * 后置通知
	 */
	@AfterReturning(pointcut = "log()", returning = "retValue")
	public void doAfterController(JoinPoint joinPoint, Object retValue) throws Throwable{
		System.out.println("after retValue is:" + retValue);
	}

	/**
	 * 后置异常通知
	 */
	@AfterThrowing("log()")
	public void throwss(JoinPoint jp){
		System.out.println("方法异常时执行.....");
	}

	/**
	 * 后置最终通知,final增强，不管是抛出异常或者正常退出都会执行
	 */
	@After("log()")
	public void after(JoinPoint jp){
		System.out.println("方法最后执行.....");
	}

	/**
	 * 环绕通知,环绕增强，相当于MethodInterceptor
	 */
	@Around("log()")
	public Object arround(ProceedingJoinPoint pjp) throws Throwable{
		System.out.println("方法环绕start.....");
		try {
			Object o =  pjp.proceed();
			System.out.println("方法环绕proceed，结果是 :" + o);
			return o;
		} catch (Throwable e) {
			throw e;
		}
	}

}
